package com.airena.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MailUtil {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private JavaMailSender mailSender;
    
    @Autowired
    private MailProperties mailProperties;
    
    /**
     * 生成并存储验证码到Redis
     * @param mail 邮箱地址
     * @return 生成的验证码
     */
    public String generateAndStoreVerificationCode(String mail) {
        // 生成6位随机数字验证码
        String code = String.format("%06d", (int) (Math.random() * 1000000));
        
        // 存储到Redis，设置5分钟过期时间
        String key = "verification_code:" + mail;
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        
        log.info("为邮箱 {} 生成验证码: {}", mail, code);
        return code;
    }
    
    /**
     * 发送邮件验证码
     * @param to 收件人邮箱
     * @param code 验证码
     */
    public void sendVerificationCode(String to, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(mailProperties.getUsername());
            message.setTo(to);
            message.setSubject("AIrena 邮箱验证码");
            message.setText("您的验证码是: " + code + "，5分钟内有效。如非本人操作请忽略。");
            
            mailSender.send(message);
            log.info("验证码邮件已发送至: {}", to);
        } catch (Exception e) {
            log.error("发送邮件失败: {}", e.getMessage(), e);
            throw new RuntimeException("邮件发送失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证验证码
     * @param mail 邮箱地址
     * @param code 用户输入的验证码
     * @return 验证结果
     */
    public boolean verifyCode(String mail, String code) {
        String key = "verification_code:" + mail;
        String storedCode = (String) redisTemplate.opsForValue().get(key);
        
        if (storedCode == null) {
            log.warn("验证码已过期或不存在: {}", mail);
            return false;
        }
        
        boolean result = storedCode.equals(code);
        if (result) {
            // 验证成功后删除验证码
            redisTemplate.delete(key);
            log.info("邮箱 {} 验证码验证成功", mail);
        } else {
            log.warn("邮箱 {} 验证码验证失败", mail);
        }
        
        return result;
    }
}